<template>
  <div class="material-list">
    <!-- 搜索栏 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input v-model="materialName" placeholder="请输入材质名称"></el-input>
      </el-col>
      <el-col :span="16" style="text-align: right;">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleAdd" class="add-button">添加</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="materials" style="width: 100%; margin-bottom: 20px;" stripe border>
      <el-table-column prop="id" label="材质编号" width="180"></el-table-column>
      <el-table-column prop="material_name" label="材质名称" width="180"></el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="180"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="totalItems"
      :current-page.sync="currentPage"
      @current-change="handlePageChange"
      style="text-align: center;"
    ></el-pagination>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {queryMaterial, deleteMaterial} from '@/api/material.js';
// 引入路由
import {useRouter} from "vue-router";

const router = useRouter();

const materialName = ref('');
const materials = ref([]);
onMounted(() => {
  fetchData();
});

async function fetchData() {
  const res = await queryMaterial();
  materials.value = res.data;
}

const totalItems = ref(100);
const currentPage = ref(1);

const handleSearch = () => {
  console.log('Search:', materialName.value);
};

const handleReset = () => {
  materialName.value = '';
};

const handleEdit = (index, row) => {
  console.log('Edit:', index, row);
};
const handleDelete = async (index, row) => {
  try {
    await deleteMaterial(row.material_name);
    materials.value.splice(index, 1);
    totalItems.value--;
  } catch (error) {
    console.error('删除材质失败:', error);
  }
};
const handleAdd = () => {
  router.push('/material/add');
};

const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style scoped>
.material-list {
  padding: 20px;
}

/* 调整按钮间距 */
.add-button {
  margin-left: 10px;
}

/* 表格样式调整 */
.el-table {
  font-size: 14px;
}

/* 分页样式调整 */
.el-pagination {
  margin-top: 20px;
}
</style>
